import {
  Button,
  Col,
  Drawer,
  Form,
  Input,
  message,
  Radio,
  Row,
  Select,
  Space,
} from "antd";
import { forwardRef, useImperativeHandle, useMemo, useState } from "react";
import BaseUpload from "@/components/base-upload";
import { useRequest } from "ahooks";
import { getRoleList } from "@/services/role.ts";
import { addUser } from "@/services/user.ts";

export type OpDrawerInit = {
  open: () => void;
};

export type OpDrawerProps = {
  onSuccess: () => void;
};

// forwardRef<T, R>
//    T - 对外暴露的类型
//    R - 组件接受的 props 的类型
const OpDrawer = forwardRef<OpDrawerInit, OpDrawerProps>(
  ({ onSuccess }, ref) => {
    const [visible, setVisible] = useState(false);
    // 表单实例对象
    const [formIns] = Form.useForm();

    // 打开
    const open = () => {
      setVisible(true);
    };

    // 关闭
    const close = () => {
      setVisible(false);
    };

    // 保存
    const onSave = async () => {
      // 1. 表单校验
      await formIns.validateFields();
      // 2. 获取 values
      const values = formIns.getFieldsValue();
      // 3. 调用接口
      await addUser(values);
      // 4. 提示成功
      message.success("保存成功");
      // 5. 提供父组件更新
      onSuccess();
      // 6. 保存Drawer
      close();
    };

    // 获取角色列表
    const { data } = useRequest(getRoleList);
    // 角色选项
    const roleOptions = useMemo(() => {
      const list = data ? data.list : [];
      // 转换成 Select 组件需要的数据格式 [{value: '', label: ''}, {value: '', label: ''}]
      return list.map((item) => ({ value: item.id, label: item.name }));
    }, [data]);

    // 对外暴露
    useImperativeHandle(ref, () => ({ open }), []);

    const footer = (
      <Space style={{ display: "flex", justifyContent: "flex-end" }}>
        <Button type="default" onClick={close}>
          取消
        </Button>
        <Button type="primary" onClick={onSave}>
          保存
        </Button>
      </Space>
    );

    return (
      <Drawer
        open={visible}
        title="新增"
        width={500}
        footer={footer}
        onClose={close}
      >
        <Form
          form={formIns}
          initialValues={{ status: 1 }}
          labelCol={{ span: 10 }}
        >
          <Row>
            <Col span={24}>
              <Form.Item label="头像" name="headImg" labelCol={{ span: 5 }}>
                <BaseUpload
                  onSuccess={(img) => {
                    // 将 img 设置到 表单的 value 上
                    formIns.setFieldValue("headImg", img);
                  }}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row>
            <Col span={12}>
              <Form.Item
                label="姓名"
                name="name"
                rules={[{ required: true, message: "必须" }]}
              >
                <Input placeholder="请输入姓名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="昵称"
                name="nickName"
                rules={[{ required: true, message: "必须" }]}
              >
                <Input placeholder="请输入昵称" />
              </Form.Item>
            </Col>
          </Row>

          <Row>
            <Col span={12}>
              <Form.Item
                label="用户名"
                name="username"
                rules={[{ required: true, message: "必须" }]}
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true, message: "必须" }]}
              >
                <Input placeholder="请输入密码" />
              </Form.Item>
            </Col>
          </Row>

          <Row>
            <Col span={24}>
              <Form.Item
                label="角色"
                name="roleIdList"
                labelCol={{ span: 5 }}
                rules={[{ required: true, message: "必须" }]}
              >
                <Select
                  mode="multiple"
                  placeholder="请输入角色"
                  options={roleOptions}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row>
            <Col span={12}>
              <Form.Item
                label="手机号码"
                name="phone"
                rules={[
                  {
                    // 通过 pattern 属性，配置一个正则表达式，输入值需要符合该表达式才通过校验
                    pattern: /^1\d{10}$/,
                    message: "请输入正确的手机号码",
                  },
                ]}
              >
                <Input placeholder="请输入手机号码" maxLength={11} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="邮箱"
                name="email"
                rules={[{ type: "email", message: "请输入正确的邮箱" }]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
          </Row>

          <Row>
            <Col span={24}>
              <Form.Item label="备注" name="remark" labelCol={{ span: 5 }}>
                <Input.TextArea placeholder="请输入备注" />
              </Form.Item>
            </Col>
          </Row>

          <Row>
            <Col span={24}>
              <Form.Item label="状态" name="status" labelCol={{ span: 5 }}>
                <Radio.Group>
                  <Radio value={1}>开启</Radio>
                  <Radio value={0}>关闭</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Drawer>
    );
  }
);

export default OpDrawer;
